package com.splant.android.smart.UILevel.Community.fragments;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.ModelLevel.DetectorListBean;
import com.splant.android.smart.ModelLevel.ParaDatasBean;
import com.splant.android.smart.ModelLevel.event.AddPageEvent;

import org.apache.http.Header;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.event.EventBus;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;

@SuppressLint("ValidFragment")
public class Garden_DetectorDatas_Fragment extends Fragment {

    private DetectorListBean.Detector detector;
    private int paraType;
    private final int PAGESIZE = 12;
    private int pageNo;

    public static Garden_DetectorDatas_Fragment newInstance(DetectorListBean.Detector detector, int paraType, int pageNo) {

        Garden_DetectorDatas_Fragment garden_detectorDatas_fragment=new Garden_DetectorDatas_Fragment();

        Bundle bundle = new Bundle();
        bundle.putSerializable("detector",detector);
        bundle.putInt("paraType",paraType);
        bundle.putInt("pageNo",pageNo);

        garden_detectorDatas_fragment.setArguments(bundle);

        return garden_detectorDatas_fragment;
    }
    public Garden_DetectorDatas_Fragment()
    {

    }

    public Garden_DetectorDatas_Fragment(DetectorListBean.Detector detector, int paraType, int pageNo) {

        this.detector = detector;
        this.paraType = paraType;
        this.pageNo = pageNo;

        getPlantMaxMinValue(detector.getTempRange());
    }

    private void getPlantMaxMinValue(String valueRange)
    {
        try
        {
            String[] values=valueRange.split(",");
            plantMinValue=Float.parseFloat(values[0]);
            plantMaxValue=Float.parseFloat(values[1]);
        }
        catch (Exception e)
        {

        }
    }

    private View mView;
    private LineChartView lineChart;
    private ColumnChartView columnChart;
    private TextView tv_startTime;
    private TextView tv_endTime;

    private sPlantAsyncHttpClient sPlantClient;
    private List<ParaDatasBean.ParaData> paraDataList = new ArrayList<>();

    private TextView tv_endPage;
    private RelativeLayout rl_times;
    private LinearLayout rl_humidityExplain;
    private LinearLayout rl_nutrientExplain;

    private RelativeLayout rl_plantMinMaxValue;
    private TextView tv_plantMinValue;
    private TextView tv_plantMaxValue;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (mView == null) {

            mView = inflater.inflate(R.layout.garden_detectordatas_fragment, container, false);
            lineChart = (LineChartView) mView.findViewById(R.id.line_chart);
            columnChart = (ColumnChartView) mView.findViewById(R.id.column_chart);

            tv_startTime = (TextView) mView.findViewById(R.id.tv_startTime);
            tv_endTime = (TextView) mView.findViewById(R.id.tv_endTime);
            tv_endPage = (TextView) mView.findViewById(R.id.tv_endPage);
            rl_times = (RelativeLayout) mView.findViewById(R.id.rl_times);

            rl_humidityExplain = (LinearLayout) mView.findViewById(R.id.rl_humidityExplain);
            rl_nutrientExplain = (LinearLayout) mView.findViewById(R.id.rl_nutrientExplain);
            rl_plantMinMaxValue= (RelativeLayout) mView.findViewById(R.id.rl_plantMinMaxValue);
            tv_plantMinValue= (TextView) mView.findViewById(R.id.tv_plantMinValue);
            tv_plantMaxValue= (TextView) mView.findViewById(R.id.tv_plantMaxValue);

            sPlantClient = sPlantAsyncHttpClient.getInstance();

            if (pageNo == 0)
                getDatas();

            if (pageNo == 10) {
                tv_endPage.setVisibility(View.VISIBLE);
            }
        }

        return mView;
    }

    public void getDatas() {

        RequestParams params = new RequestParams();
        params.put("detectorId", detector.getDetectorId());
        params.put("pageSize", PAGESIZE);
        params.put("pageNo", pageNo);
        params.put("orgData",true);

        sPlantClient.get(sPlantAsyncHttpClient.GETDETECTORDATAS, params, new sPlantJsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try
                {
                    if (response.getInt("succeed") == 1) {

                        paraDataList.clear();

                        Gson gson = new Gson();
                        ParaDatasBean paraDatasBean = gson.fromJson(response.toString(), ParaDatasBean.class);

                        if (paraDatasBean.getParaDatas() != null)
                            paraDataList.addAll(paraDatasBean.getParaDatas());

                        showGraphical();

                        if (paraDataList.size() == PAGESIZE) {
                            EventBus.getDefault().post(new AddPageEvent());
                        } else {
                            Toast.makeText(getActivity(), "没有数据了", Toast.LENGTH_SHORT).show();
                        }

                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void selectedPara(int paraType) {
        if (this.paraType != paraType) {
            this.paraType = paraType;
            showGraphical();
        }
    }

    private void showGraphical() {

        if (paraDataList.size() > 0)
        {
            if (paraType == 0)
            {
                showTemperatureLineChart();
            }
            else if (paraType == 1)
            {
                showSoilHumidityColumnChart();
                rl_plantMinMaxValue.setVisibility(View.GONE);
            }
            else if (paraType == 2)
            {
                showSoilNutrientColumnChart();
                rl_plantMinMaxValue.setVisibility(View.GONE);
            }

            rl_times.setVisibility(View.VISIBLE);
            tv_startTime.setText(paraDataList.get(0).getCreateDate());
            tv_endTime.setText(paraDataList.get(paraDataList.size() - 1).getCreateDate());

            rl_humidityExplain.setVisibility(View.GONE);
            rl_nutrientExplain.setVisibility(View.GONE);

            if (paraType == 2) {
                rl_nutrientExplain.setVisibility(View.VISIBLE);
            }

        } else {
            hideView();
        }
    }

    private List<PointValue> mPointValues_tp = new ArrayList<PointValue>();
    private List<PointValue> mPointValues_sh = new ArrayList<PointValue>();

    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();

    private void getTemperatureAxisPoints(List<ParaDatasBean.ParaData> paraDataList) {

        mPointValues_tp.clear();
        for (int i = 0; i < paraDataList.size(); i++) {

            float value=Float.parseFloat(paraDataList.get(i).getSoilTemperature());
            mPointValues_tp.add(new PointValue(i,value));

            if (LINE_MAXVALUE_TP==PLANT_MAXMIN_DEFAULTVALUE)
                LINE_MAXVALUE_TP= (int) (value+1);
            else
            {
                if (value>LINE_MAXVALUE_TP)
                    LINE_MAXVALUE_TP= (int) (value+1);
            }

            if (LINE_MINVALUE_TP==PLANT_MAXMIN_DEFAULTVALUE)
                LINE_MINVALUE_TP= (int) (value-1);
            else
            {
                if (value<LINE_MINVALUE_TP)
                    LINE_MINVALUE_TP= (int) (value-1);
            }
        }
//        if (LINE_MINVALUE_TP>plantMinValue&&plantMinValue!=PLANT_MAXMIN_DEFAULTVALUE)
//            LINE_MINVALUE_TP= (int) (plantMinValue-1);

    }

    private void getSoilHumidityAxisPoints(List<ParaDatasBean.ParaData> paraDataList) {

        mPointValues_sh.clear();

        for (int i = 0; i < paraDataList.size(); i++) {

            float value=Float.parseFloat(paraDataList.get(i).getSoilHumidity());
            mPointValues_sh.add(new PointValue(i,value));

            if (LINE_MAXVALUE_SH==PLANT_MAXMIN_DEFAULTVALUE)
                LINE_MAXVALUE_SH= (int) (value+1);
            else
            {
                if (value>LINE_MAXVALUE_SH)
                    LINE_MAXVALUE_SH= (int) (value+1);
            }

            if (LINE_MINVALUE_SH==PLANT_MAXMIN_DEFAULTVALUE)
                LINE_MINVALUE_SH= (int) (value-1);
            else
            {
                if (value<LINE_MINVALUE_SH)
                    LINE_MINVALUE_SH= (int) (value-1);
            }
            //mAxisXValues.add(new AxisValue(i).setLabel(String.valueOf(Float.parseFloat(paraDataList.get(i).getSoilTemperature()))));
        }
    }

    private final int PLANT_MAXMIN_DEFAULTVALUE=-1000;

    private  int LINE_MAXVALUE_TP=PLANT_MAXMIN_DEFAULTVALUE;
    private  int LINE_MINVALUE_TP=PLANT_MAXMIN_DEFAULTVALUE;

    private  int LINE_MAXVALUE_SH=PLANT_MAXMIN_DEFAULTVALUE;
    private  int LINE_MINVALUE_SH=PLANT_MAXMIN_DEFAULTVALUE;

    private float plantMaxValue=PLANT_MAXMIN_DEFAULTVALUE;
    private float plantMinValue=PLANT_MAXMIN_DEFAULTVALUE;

    private void showTemperatureLineChart() {

        lineChart.setVisibility(View.VISIBLE);
        columnChart.setVisibility(View.GONE);

        getTemperatureAxisPoints(paraDataList);

        List<Line> lines = new ArrayList<Line>();
        Line line = new Line(mPointValues_tp).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(false);//曲线是否平滑，即是曲线还是折线
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(false);//曲线的数据坐标是否加上备注
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
        line.setHasLabelsOnlyForSelected(false);
        lines.add(line);

        if (plantMaxValue!=PLANT_MAXMIN_DEFAULTVALUE)
        {
//            List<PointValue> mPointMaxValues = new ArrayList<PointValue>();
//
//            for (int i=0;i<paraDataList.size();i++)
//                mPointMaxValues.add(new PointValue(i,plantMaxValue));
//
//            Line maxLine=new Line(mPointMaxValues).setColor(Color.parseColor("#0000FF"));
//            maxLine.setCubic(false);//曲线是否平滑，即是曲线还是折线
//            maxLine.setFilled(false);//是否填充曲线的面积
//            maxLine.setHasLabels(false);//曲线的数据坐标是否加上备注
//            maxLine.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
//            maxLine.setHasPoints(false);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
//            maxLine.setHasLabelsOnlyForSelected(false);
//            lines.add(maxLine);

            rl_plantMinMaxValue.setVisibility(View.VISIBLE);
            tv_plantMaxValue.setText(String.valueOf(plantMaxValue)+"℃");
        }

        if (plantMinValue!=PLANT_MAXMIN_DEFAULTVALUE)
        {
//            List<PointValue> mPointMinValues = new ArrayList<PointValue>();
//            for (int i=0;i<paraDataList.size();i++)
//                mPointMinValues.add(new PointValue(i,plantMinValue));
//
//            Line minLine=new Line(mPointMinValues).setColor(Color.parseColor("#FF0000"));
//            minLine.setCubic(false);//曲线是否平滑，即是曲线还是折线
//            minLine.setFilled(false);//是否填充曲线的面积
//            minLine.setHasLabels(false);//曲线的数据坐标是否加上备注
//            minLine.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
//            minLine.setHasPoints(false);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
//            minLine.setHasLabelsOnlyForSelected(false);
//            lines.add(minLine);
            tv_plantMinValue.setVisibility(View.VISIBLE);
            tv_plantMinValue.setText(String.valueOf(plantMinValue)+"℃");
        }

        LineChartData dataLine = new LineChartData();
        dataLine.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setTextColor(Color.BLUE);  //设置字体颜色
        axisX.setTextSize(8);//设置字体大小
        axisX.setMaxLabelChars(12); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        dataLine.setAxisXBottom(axisX); //x 轴在底部
        axisX.setHasLines(false); //x 轴分割线

        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();  //Y轴
        axisY.setTextSize(8);//设置字体大小
        axisY.setHasLines(true);// 是否显示Y轴网格线
        axisY.setTextColor(Color.BLUE);
        dataLine.setAxisYLeft(axisY);  //Y轴设置在左边

        //设置行为属性，支持缩放、滑动以及平移
        lineChart.setInteractive(false);
        lineChart.setLineChartData(dataLine);

        Viewport v= new Viewport(lineChart.getMaximumViewport());
        v.top = LINE_MAXVALUE_TP;
        v.bottom =LINE_MINVALUE_TP;

        lineChart.setMaximumViewport(v);
        lineChart.setCurrentViewport(v);
    }

    private void showSoilHumidityColumnChart()
    {
        lineChart.setVisibility(View.VISIBLE);
        columnChart.setVisibility(View.GONE);

        getSoilHumidityAxisPoints(paraDataList);

        List<Line> lines = new ArrayList<Line>();
        Line line = new Line(mPointValues_sh).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(false);//曲线是否平滑，即是曲线还是折线
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(false);//曲线的数据坐标是否加上备注
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
        line.setHasLabelsOnlyForSelected(false);
        lines.add(line);

        LineChartData dataLine = new LineChartData();
        dataLine.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setTextColor(Color.BLUE);  //设置字体颜色
        axisX.setTextSize(8);//设置字体大小
        axisX.setMaxLabelChars(12); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        dataLine.setAxisXBottom(axisX); //x 轴在底部
        axisX.setHasLines(false); //x 轴分割线

        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();  //Y轴
        axisY.setTextSize(8);//设置字体大小
        axisY.setHasLines(true);// 是否显示Y轴网格线
        axisY.setTextColor(Color.BLUE);
        axisY.setAutoGenerated(true);
        dataLine.setAxisYLeft(axisY);  //Y轴设置在左边

        //设置行为属性，支持缩放、滑动以及平移
        lineChart.setInteractive(false);
        lineChart.setLineChartData(dataLine);


        Viewport v = new Viewport(lineChart.getMaximumViewport());
        v.top = LINE_MAXVALUE_SH;
        v.bottom =LINE_MINVALUE_SH;

        lineChart.setMaximumViewport(v);
        lineChart.setCurrentViewport(v);
    }

//    private void showSoilHumidityColumnChart() {
//
//        lineChart.setVisibility(View.GONE);
//        columnChart.setVisibility(View.VISIBLE);
//
//        // 使用的 7列，每列1个subcolumn。
//        int numSubcolumns = 1;
//        int numColumns = 12;
//        //定义一个圆柱对象集合
//        List<Column> columns = new ArrayList<Column>();
//        //子列数据集合
//        List<SubcolumnValue> values;
//        List<AxisValue> axisValues = new ArrayList<AxisValue>();
//        //遍历列数numColumns
//        for (int i = 0; i < numColumns; ++i) {
//            values = new ArrayList<SubcolumnValue>();
//            //遍历每一列的每一个子列
//            for (int j = 0; j < numSubcolumns; ++j) {
//                //为每一柱图添加颜色和数值
//                float value = 0;
//                try {
//                    value = Float.parseFloat(paraDataList.get(i).getSoilHumidity());
//                } catch (Exception e) {
//
//                }
//                int color = 0;
//                if (value == 1)
//                    color = Color.parseColor("#FF7400");
//                else if (value == 2)
//                    color = Color.parseColor("#008000");
//                else
//                    color = Color.parseColor("#0000FF");
//
//                values.add(new SubcolumnValue(value, color));
//            }
//            //创建Column对象
//            Column column = new Column(values);
//            //是否有数据标注
//            column.setHasLabels(false);
//            //是否是点击圆柱才显示数据标注
//            column.setHasLabelsOnlyForSelected(true);
//            columns.add(column);
//            //给x轴坐标设置描述
//        }
//        //创建一个带有之前圆柱对象column集合的ColumnChartData
//        ColumnChartData data = new ColumnChartData(columns);
//
//        //定义x轴y轴相应参数
//        Axis axisX = new Axis();
//        Axis axisY = new Axis().setHasLines(false);
//
//        axisY.setName("");//轴名称
//        axisY.hasLines();//是否显示网格线
//        axisY.setMaxLabelChars(3);
//        axisX.hasLines();
//        axisX.setValues(axisValues);
//
//        //把X轴Y轴数据设置到ColumnChartData 对象中
//        data.setAxisXBottom(axisX);
//        // data.setAxisYLeft(axisY);
//        //给表填充数据，显示出来
//        columnChart.setColumnChartData(data);
//        columnChart.setInteractive(false);
//
//        Viewport v = new Viewport(columnChart.getMaximumViewport());
////        v.left = 0;
////        v.right= 12;
//        v.top=3;
//        v.bottom=0;
//
//        columnChart.setMaximumViewport(v);
//        columnChart.setCurrentViewport(v);
//    }

    private void showSoilNutrientColumnChart() {

        lineChart.setVisibility(View.GONE);
        columnChart.setVisibility(View.VISIBLE);

        // 使用的 7列，每列1个subcolumn。
        int numSubcolumns = 1;
        int numColumns = 12;
        //定义一个圆柱对象集合
        List<Column> columns = new ArrayList<Column>();
        //子列数据集合
        List<SubcolumnValue> values;
        List<AxisValue> axisValues = new ArrayList<AxisValue>();
        //遍历列数numColumns
        for (int i = 0; i < numColumns; ++i) {
            values = new ArrayList<SubcolumnValue>();
            //遍历每一列的每一个子列
            for (int j = 0; j < numSubcolumns; ++j) {
                //为每一柱图添加颜色和数值
                float value = 0;
                try {
                    value = Float.parseFloat(paraDataList.get(i).getSoilNutritent());
                } catch (Exception e) {

                }
                int color = 0;
                if (value == 1)
                    color = Color.parseColor("#FF7400");
                else if (value == 2)
                    color = Color.parseColor("#008000");
                else
                    color = Color.parseColor("#0000FF");

                values.add(new SubcolumnValue(value, color));
            }
            //创建Column对象
            Column column = new Column(values);
            //是否有数据标注
            column.setHasLabels(false);
            //是否是点击圆柱才显示数据标注
            column.setHasLabelsOnlyForSelected(true);
            columns.add(column);
            //给x轴坐标设置描述
        }

        //创建一个带有之前圆柱对象column集合的ColumnChartData
        ColumnChartData data = new ColumnChartData(columns);

        //定义x轴y轴相应参数
        Axis axisX = new Axis();
        Axis axisY = new Axis().setHasLines(true);

        axisY.setName("");//轴名称
        axisY.hasLines();//是否显示网格线
        axisY.setMaxLabelChars(3);
        axisX.hasLines();
        axisX.setValues(axisValues);

        //把X轴Y轴数据设置到ColumnChartData 对象中
        data.setAxisXBottom(axisX);
        //data.setAxisYLeft(axisY);
        //给表填充数据，显示出来
        columnChart.setColumnChartData(data);
        columnChart.setInteractive(false);

        Viewport v = new Viewport(columnChart.getMaximumViewport());
//        v.left = 0;
//        v.right= 12;
        v.top=3;
        v.bottom=0;

        columnChart.setMaximumViewport(v);
        columnChart.setCurrentViewport(v);
    }

    private void hideView() {
        lineChart.setVisibility(View.GONE);
        columnChart.setVisibility(View.GONE);
        tv_startTime.setText("");
        tv_endTime.setText("");
    }

}
